﻿using System;
using System.Data;
using System.Windows.Forms;
using BadgeManager.Controller;
using BadgeManager.Model;

namespace Badge_Manager.View
{
    public partial class frmStoricoEntrate : Form
    {
        private DataTable dtStoricoEntrate;
        private Utente Utente;
        private Timer Timer;

        public frmStoricoEntrate(Utente utente)
        {
            InitializeComponent();
            Timer = new Timer();
            Timer.Tick += new EventHandler(Timer_Tick);
            this.Utente = utente;
            Elenco(dtDataFiltro.Value);
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            cmdAggiorna_Click(null, null);
        }

        private void Elenco(DateTime datacondizione)
        {
            dtStoricoEntrate = new DataTable();
            ctrlStoricoEntrate cStorico = new ctrlStoricoEntrate();

            dtStoricoEntrate = cStorico.SelezionaTutto("( dataentrata='" + datacondizione + "' AND codicetessera like '%" + txtCodiceTessera.Text + "%')", "ora asc");

            grid.DataSource = null;
            grid.DataSource = dtStoricoEntrate;
            FormattaGriglia();
        }

        private void FormattaGriglia()
        {
            grid.Columns["Id"].Visible = false;
            grid.Columns["Entrata"].DefaultCellStyle.Format = "dddd dd MMMM yyyy";
        }

        private void dtDataFiltro_ValueChanged(object sender, EventArgs e)
        {
            Elenco(dtDataFiltro.Value);
        }

        private void cmdAnnulla_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtCodiceTessera_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                Elenco(dtDataFiltro.Value);
                txtCodiceTessera.Text = "";
            }
        }

        private void cmdAggiorna_Click(object sender, EventArgs e)
        {
            Elenco(dtDataFiltro.Value);
        }

        private void AttivaTimer(bool ok)
        {
            Timer.Interval = Properties.Settings.Default.TimerIntervalRefreshBadge;
            if (ok)
            {
                Timer.Enabled = true;
                Timer.Start();
            }
            else
            {
                Timer.Enabled = false;
                Timer.Stop();
            }
        }

        private void frmStoricoEntrate_FormClosing(object sender, FormClosingEventArgs e)
        {
            AttivaTimer(false);
        }

        private void chkAggiornaAutom_CheckStateChanged(object sender, EventArgs e)
        {
            AttivaTimer(chkAggiornaAutom.Checked);
        }

        private void txtCodiceTessera_TextChanged(object sender, EventArgs e)
        {
        }
    }
}